import 'dart:async';

import 'package:ycbl/net/http/bl_request_manager.dart';
import 'package:ycbl/widget/provider/base_view_state_model.dart';

class SendCodeViewModel extends BaseViewStateModel{

  /// 倒计时总时间，默认 60s
  final int maxSeconds;

  Timer _timer;
  int currTime;

  /// 倒计时是否结束
  bool get isFinish => currTime == maxSeconds;

  /// 准备开始倒计时，在准备开始之前，应该和 busy UI 效果一致，转圈圈
  bool isPreCountdown = false;

  SendCodeViewModel({this.maxSeconds = 60}){
    currTime = maxSeconds;
  }

  /// 发送验证码
  sendCode(String phone, Function(bool) callBack) {
    setBusy();
    BLRequestManager.getInstance().get('?s=Ycsc.User.sendCode', queryParameters: {'phone': phone}, onSuccess: (json){

      if(json['data'] == true) {
        isPreCountdown = true;
        setIdle();
        callBack(true);
        _startCountDown();
      }else {
        setError(json['msg'] ?? '获取验证码失败');
        callBack(false);
      }

    }, onError: (error){
      setError(error);
      callBack(false);
    });

  }

  ///开始倒计时
  _startCountDown(){
    cancelTimer();
    // periodic 指定每一秒回调一下
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if(isPreCountdown) {
        isPreCountdown = false;
      }
      if (timer.tick == maxSeconds) {//倒计时结束
        cancelTimer();
        currTime = maxSeconds;
      }else {
        currTime--;
      }
      //通知变化
      notifyListeners();
    },);
  }

  /// 取消倒计时
  cancelTimer() {
    if (_timer != null) {
      _timer.cancel();
      _timer = null;
    }
  }

  @override
  void onDisposed() {
    cancelTimer();
    super.onDisposed();
  }

}